package com.bird.thread.base.thread;

/**
 * @author sijunqiang
 * @data 2021/6/30 21:50
 * @description: 演示 wait 只会释放当前的那把锁。
 */
public class WaitNotifyReleaseOwnMonitor {


    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resourceA) {
                    System.out.println("ThreadA got resourceA lock.");

                    synchronized (resourceB) {
                        System.out.println("ThreadA got resourceB lock.");

                        try {
                            System.out.println("ThreadA releases resourceA lock.");
                            //那个线程调用这个对象锁的wait()方法。这个线程就是进行阻塞状态 释放掉这把对象锁。
                            resourceA.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (resourceA) {
                    System.out.println("ThreadB got resourceA lock.");
                    System.out.println("ThreadB tries to resourceB lock.");

                    synchronized (resourceB) {
                        System.out.println("ThreadB got resourceB lock.");
                    }
                }
            }
        });

        thread1.start();
        thread2.start();
    }

    /*结论：
     *1： wait()方法 只会释放当前的那个线程拥有的锁。
     *2： 一个线程可以拥有不同对象的锁,且每个锁都知道自己的所有者是那个线程，每个锁都有独立的计数器。
     *3：这就是为什么 线程一直处于阻塞状态的原因。
     *
     */
}
